package net.suncaper.hotel.web.controller;

import net.suncaper.hotel.common.framework.RequestMapping;
import net.suncaper.hotel.common.utils.JSONUtil;
import net.suncaper.hotel.common.utils.PageInfo;
import net.suncaper.hotel.common.utils.Result;
import net.suncaper.hotel.model.dto.UserDTO;
import net.suncaper.hotel.model.dto.UserLoginDTO;
import net.suncaper.hotel.model.vo.UserVO;
import net.suncaper.hotel.service.IUserService;
import net.suncaper.hotel.service.impl.UserServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;

/**
 * 用户控制器
 */
@RequestMapping("/api/user")
public class UserController {
    private IUserService userService = new UserServiceImpl();

    /**
     * 用户登录
     */
    @RequestMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取请求体
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            UserLoginDTO loginDTO = JSONUtil.fromJSON(sb.toString(), UserLoginDTO.class);
            UserVO userVO = userService.login(loginDTO);
            
            if (userVO != null) {
                // 保存到session
                HttpSession session = request.getSession();
                session.setAttribute("user", userVO);
                
                JSONUtil.printByJSON(response, Result.success("登录成功", userVO));
            } else {
                JSONUtil.printByJSON(response, Result.fail("用户名或密码错误"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("登录失败"));
        }
    }

    /**
     * 用户登出
     */
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.invalidate();
        JSONUtil.printByJSON(response, Result.success("登出成功"));
    }

    /**
     * 获取当前用户信息
     */
    @RequestMapping("/info")
    public void getUserInfo(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        UserVO user = (UserVO) session.getAttribute("user");
        if (user != null) {
            JSONUtil.printByJSON(response, Result.success(user));
        } else {
            JSONUtil.printByJSON(response, Result.error(401, "未登录"));
        }
    }

    /**
     * 获取用户列表
     */
    @RequestMapping("/list")
    public void getUserList(HttpServletRequest request, HttpServletResponse response) {
        try {
            String pageNumStr = request.getParameter("pageNum");
            String pageSizeStr = request.getParameter("pageSize");
            
            int pageNum = pageNumStr != null ? Integer.parseInt(pageNumStr) : 1;
            int pageSize = pageSizeStr != null ? Integer.parseInt(pageSizeStr) : 10;
            
            PageInfo<UserVO> pageInfo = userService.getUserList(pageNum, pageSize);
            JSONUtil.printByJSON(response, Result.success(pageInfo));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("获取用户列表失败"));
        }
    }

    /**
     * 创建用户
     */
    @RequestMapping("/create")
    public void createUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            UserDTO userDTO = JSONUtil.fromJSON(sb.toString(), UserDTO.class);
            boolean success = userService.createUser(userDTO);
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("创建用户成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("创建用户失败，用户名可能已存在"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("创建用户失败"));
        }
    }

    /**
     * 更新用户
     */
    @RequestMapping("/update")
    public void updateUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            UserDTO userDTO = JSONUtil.fromJSON(sb.toString(), UserDTO.class);
            boolean success = userService.updateUser(userDTO);
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("更新用户成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("更新用户失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("更新用户失败"));
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("/delete/*")
    public void deleteUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            String uri = request.getRequestURI();
            String idStr = uri.substring(uri.lastIndexOf("/") + 1);
            if (idStr.endsWith(".do")) {
                idStr = idStr.substring(0, idStr.length() - 3);
            }
            
            Integer id = Integer.parseInt(idStr);
            boolean success = userService.deleteUser(id);
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("删除用户成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("删除用户失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("删除用户失败"));
        }
    }
}